package com.dc.cron;

import com.dc.constant.Constants;
import com.dc.dao.AlarmDao;
import com.dc.dao.ConfigDao;
import com.dc.entity.AlarmEntity;
import com.dc.entity.ConfigEntity;
import com.dc.model.EnergyMonitorSearchBody;
import com.dc.service.EnergyMonitorService;
import com.dc.service.dto.CMonitorChildDto;
import com.dc.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * 内部监控（孖洲岛碳排放）：孖洲岛XX月份碳排放量已超限
 *                      孖洲岛XX季度碳排放量已超限
 *                      孖洲岛XX年度碳排放量已超限
 * 碳核查（孖洲岛碳排放）：友联船厂本年度碳排放量已超限
 *                    招商重工本年度碳排放量已超限
 *                    孖洲岛本年度碳排放量已超限
 * 预警等级： 预警等级现在是分两个等级，
 *          一般和严重，一般的范围在超过了指标并在指标的25％以内，严重是超过了指标的25％。
 */
@Slf4j
@Component
public class AlarmCron {

    @Resource
    AlarmDao alarmDao;

    @Resource
    ConfigDao configDao;

    @Resource
    EnergyMonitorService energyMonitorService;

    @Scheduled(cron = "0 5 0  * * ?")
    public void alarm() {

        log.info("alarm enter ~~~~~~~");

        Integer year = DateUtils.getYear();
        Date now = DateUtils.getNowDate();
//        Integer year = 2024;
//        Date now = DateUtils.dateTime("yyyy-MM-dd", "2024-10-01");

        // 内部监控
        monitorIn(year, now);
        // 碳核查  友联船厂  招商重工  孖洲岛
        monitorCMonitor(year, now, Constants.NAME_COMPANY_YOU);
        monitorCMonitor(year, now, Constants.NAME_COMPANY_ZHAO);
        monitorCMonitor(year, now, Constants.NAME_COMPANY_ZIZHOU);

    }

    /**
     * 内部监控  孖洲岛  月  季度   年 碳排
     */
    private void monitorIn(int year, Date now) {
        // 内部监控 -- 孖洲岛
        EnergyMonitorSearchBody body = new EnergyMonitorSearchBody();
        // 设置参数
        body.setYear(year);
        body.setType(Constants.TYPE_DC_IN_MONITOR);
        body.setCompany(Constants.NAME_COMPANY_ZIZHOU);

        CMonitorChildDto cpai = null;
        CMonitorChildDto cpaiFlags = null;
        CMonitorChildDto cpaiPower = null;
        CMonitorChildDto cpaiPowerFlags = null;

        boolean flag = false;   // 是否有数据

        List<CMonitorChildDto> cMonitor = energyMonitorService.getCMonitor(body);
        for(CMonitorChildDto dto : cMonitor) {
            flag = true;    // 进入循环，必有数据
            String name = dto.getName();
            // 碳排放量月度/年度指标
            if(Constants.NAME_C_FLAG_INCLUDE.equals(name)) {
                cpaiFlags = dto;
            }

            // 碳排放量-深圳指南 行
            if(Constants.NAME_C_SHENZHEN_INCLUDE.equals(name)) {
                cpai = dto;
            }

            // 碳排放强度-因子指标
            if(Constants.NAME_C_POWER_INCLUDE.equals(name)) {
                cpaiPower = dto;
            }

            // 碳排放强度月度/年度指标
            if(Constants.NAME_C_POWER_FLAG_INCLUDE.equals(name)) {
                cpaiPowerFlags = dto;
            }
        }

        if(flag) {
            // 比较
            List<Double> cpaiMonths = cpai.getMonths();
            Double cpaiSum = cpai.getSum();

            List<Double> cpaiFlagsMonths = cpaiFlags.getMonths();
            Double cpaiFlagsSum = cpaiFlags.getSum();
            // 月
            for(int i = 0; i < 12; i++) {
                Double deltaMonth = cpaiMonths.get(i) - cpaiFlagsMonths.get(i);
                AlarmEntity entity = null;
                if(deltaMonth > Constants.ALARM_THRESHOLD * cpaiFlagsMonths.get(i)) {    // 超过了 25%，写严重预警
                    entity = new AlarmEntity(null, now, "孖洲岛" + year + "年" + (i+1) + "月份碳排放量已超限", "严重", 0, "", "");
                } else if(deltaMonth > 0) {     // 超过了，写一般预警
                    entity = new AlarmEntity(null, now, "孖洲岛" + year + "年" + (i+1) + "月份碳排放量已超限", "一般", 0, "", "");
                }
                // entity 有值，则保存
                if(ObjectUtils.isNotEmpty(entity)) {
                    alarmDao.save(entity);
                }
            }
            // 季度
            Double quarter1 = cpaiMonths.get(0) + cpaiMonths.get(1) + cpaiMonths.get(2);
            Double quarter1Flags = cpaiFlagsMonths.get(0) + cpaiFlagsMonths.get(1) + cpaiFlagsMonths.get(2);

            quarterCalc(year, now, 1, quarter1, quarter1Flags);


            Double quarter2 = cpaiMonths.get(3) + cpaiMonths.get(4) + cpaiMonths.get(5);
            Double quarter2Flags = cpaiFlagsMonths.get(3) + cpaiFlagsMonths.get(4) + cpaiFlagsMonths.get(5);

            quarterCalc(year, now, 2, quarter2, quarter2Flags);


            Double quarter3 = cpaiMonths.get(6) + cpaiMonths.get(7) + cpaiMonths.get(8);
            Double quarter3Flags = cpaiFlagsMonths.get(6) + cpaiFlagsMonths.get(7) + cpaiFlagsMonths.get(8);

            quarterCalc(year, now, 3, quarter3, quarter3Flags);

            Double quarter4 = cpaiMonths.get(9) + cpaiMonths.get(10) + cpaiMonths.get(11);
            Double quarter4Flags = cpaiFlagsMonths.get(9) + cpaiFlagsMonths.get(10) + cpaiFlagsMonths.get(11);

            quarterCalc(year, now, 4, quarter4, quarter4Flags);

            // 年
            Double deltaYear = cpaiSum - cpaiFlagsSum;
            AlarmEntity entity = null;
            if(deltaYear > Constants.ALARM_THRESHOLD * cpaiFlagsSum) {  // 超过了 25%，写严重预警
                entity = new AlarmEntity(null, now, "孖洲岛" + year + "年度碳排放量已超限", "严重", 0, "", "");
            } else if(deltaYear > 0) {
                entity = new AlarmEntity(null, now, "孖洲岛" + year + "年度碳排放量已超限", "一般", 0, "", "");
            }

            if(ObjectUtils.isNotEmpty(entity)) {
                alarmDao.save(entity);
            }

            // 碳排放强度
            List<Double> cpaiPowerMonths = cpaiPower.getMonths();
            List<Double> cpaiPowerFlagsMonths = cpaiPowerFlags.getMonths();
            for(int i = 0; i < 12; i++) {
                Double deltaMonth = cpaiPowerMonths.get(i) - cpaiPowerFlagsMonths.get(i);
                AlarmEntity entityPower = null;
                if(deltaMonth > Constants.ALARM_THRESHOLD * cpaiPowerFlagsMonths.get(i)) {    // 超过了 25%，写严重预警
                    entityPower = new AlarmEntity(null, now, "孖洲岛" + year + "年" + (i+1) + "月份碳排放强度已超限", "严重", 0, "", "");
                } else if(deltaMonth > 0) {     // 超过了，写一般预警
                    entityPower = new AlarmEntity(null, now, "孖洲岛" + year + "年" + (i+1) + "月份碳排放强度已超限", "一般", 0, "", "");
                }
                // entity 有值，则保存
                if(ObjectUtils.isNotEmpty(entityPower)) {
                    alarmDao.save(entityPower);
                }
            }
        }
    }

    /**
     * 碳核查
     * @param year
     */
    private void monitorCMonitor(int year, Date now, String company) {

        // config
        String configName = null;
        if(company.equals(Constants.NAME_COMPANY_ZIZHOU)) {
            configName = Constants.NAME_C_CHECK_QUOTA_SHENZHEN_ZI;
        } else if(company.equals(Constants.NAME_COMPANY_YOU)) {
            configName = Constants.NAME_C_CHECK_QUOTA_SHENZHEN_YOU;
        } else if(company.equals(Constants.NAME_COMPANY_ZHAO)) {
            configName = Constants.NAME_C_CHECK_QUOTA_SHENZHEN_ZHAO;
        } else {
            throw new RuntimeException("monitorCMonitor company errror , company = " + company);
        }

        // 孖洲岛
        EnergyMonitorSearchBody body = new EnergyMonitorSearchBody();
        // 设置参数
        body.setYear(year);
        body.setType(Constants.TYPE_DC_C_CHECK);
        body.setCompany(company);
        List<CMonitorChildDto> cMonitorZIZHOU = energyMonitorService.getCMonitor(body);

        boolean flag = false;
        CMonitorChildDto cpai = null;

        for(CMonitorChildDto dto : cMonitorZIZHOU) {
            flag = true;    // 进入循环，必有数据
            String name = dto.getName();
            // 碳排放量月度/年度指标
            if(Constants.NAME_C_SHENZHEN_INCLUDE.equals(name)) {
                cpai = dto;
            }
        }

        if(flag) {
            Double cpaiSum = cpai.getSum();
            ConfigEntity config = configDao.findByYearAndName(year, configName);
            Double cpaiSumFlags = 0.;
            if(ObjectUtils.isNotEmpty(config)) {
                cpaiSumFlags = config.getValue();
            }

            Double deltaYear = cpaiSum - cpaiSumFlags;
            AlarmEntity entity = null;
            if(deltaYear > Constants.ALARM_THRESHOLD * cpaiSumFlags) {  // 超过了 25%，写严重预警
                entity = new AlarmEntity(null, now, company + year + "年度碳排放量已超限", "严重", 0, "", "");
            } else if(deltaYear > 0) {
                entity = new AlarmEntity(null, now, company + year + "年度碳排放量已超限", "一般", 0, "", "");
            }

            if(ObjectUtils.isNotEmpty(entity)) {
                alarmDao.save(entity);
            }
        }
    }


    /**
     * 月度计算  孖洲岛
     * @param year
     * @param now
     * @param quarterNumer
     * @param quarter
     * @param quarterFlags
     */
    private void quarterCalc(int year, Date now, int quarterNumer, Double quarter, Double quarterFlags) {
        Double deltaQuarter = quarter - quarterFlags;
        AlarmEntity entity = null;
        if(deltaQuarter > Constants.ALARM_THRESHOLD * quarterFlags) {    // 超过了 25%，写严重预警
            entity = new AlarmEntity(null, now, "孖洲岛" + year + "年" + quarterNumer + "季度碳排放量已超限", "严重", 0, "", "");
        } else if(deltaQuarter > 0) {     // 超过了，写一般预警
            entity = new AlarmEntity(null, now, "孖洲岛" + year + "年" + quarterNumer + "季度碳排放量已超限", "一般", 0, "", "");
        }
        // entity 有值，则保存
        if(ObjectUtils.isNotEmpty(entity)) {
            alarmDao.save(entity);
        }
    }
}
